/*
 * Copyright (c) 2009, Jan Pastor. All Rights Reserved.
 */

package sk.jp.jitag.proc;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import sk.jp.commons.utils.BackgroundProcess;
import sk.jp.commons.utils.LogMsg;
import sk.jp.jitag.util.Msg;
import sk.jp.jitag.ApplicationLogic;
import sk.jp.jitag.vo.RepositoryScanStatistics;

/**
 * Background process that performs repository refresh - synchronize internal
 * file database with real files.
 */
public class RepositoryRefreshProcess extends BackgroundProcess {

    private static final Logger log = LoggerFactory.getLogger(RepositoryRefreshProcess.class);

    private final ApplicationLogic applicationLogic;
    private String info;

    //----------------------------------------------------------------------

    public RepositoryRefreshProcess(ApplicationLogic applicationLogic,
                                    StateHandler... stateHandler) {
        super(stateHandler);
        this.applicationLogic = applicationLogic;
        this.info = Msg.repositoryRefreshProcessInfo.value();
    }

    //----------------------------------------------------------------------

    public boolean isCancellable() {
        return true;
    }

    public String getInfo() {
        return info;
    }

    public void run() {
        try {
            processStarted();

            RepositoryScanStatistics scanStatistics = applicationLogic.scanRepositories(this);
            boolean cancelled = scanStatistics == null;
            if(cancelled){
                processCancelled();
                return;
            }

            //update info presentd on finish
            StringBuilder buf = new StringBuilder(info);
            info = buf.append(" (N: ").append(scanStatistics.getNewCount())
                .append(", U: ").append(scanStatistics.getUpdatedCount())
                .append(", D: ").append(scanStatistics.getDeletedCount())
                .append(", S: ").append(scanStatistics.getNochangeCount())
                .append(", A: ").append(scanStatistics.getNewCount()
                                        +scanStatistics.getUpdatedCount()
                                        +scanStatistics.getNochangeCount())
                .append(")").toString();

            processFinished();
        }catch(Throwable t){
            log.error("Unexpected exception during performing background process", t);
            processFinishedWithError(t);
        }
    }

}